﻿/*
 *  invocations.js
 *
 *  A jQuery plugin to handle changes to the character known invocations list.
 */
 (function ($) {
     var settings = {
         updateInvocationUrl: '',
         invocationUpdatedCallback: null,
         refreshInvocationsUrl: '',
         invocationsContainer: '.invocations-container',
         invocationsCallback: null,
         knownInvocationLimits: null,
         sectsUrl: '',
         sectsContainerSelector: '',
         sectsRefreshedCallback: null
     };

     var methods = {
         init: function (options) {
             settings = $.extend(settings, options);

             bindInvocations();
         },
         refreshSects: function (content) {
             _refreshSects();
         },
         refreshInvocations: function (content) {
             _refreshInvocations();
         } 
     };


     $.fn.invocations = function (method) {

         // Method calling logic
         if (methods[method]) {
             return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
         } else if (typeof method === 'object' || !method) {
             return methods.init.apply(this, arguments);
         } else {
             $.error('Method ' + method + ' does not exist on invocations object.');
         }

     };

     function bindInvocations() {
         // bind the knwon invocation check box to detect when any selection changes.
         $('input.invocation-selected', settings.invocationsContainer).each(function () {
             $(this).change(function () {
                 // get row parent and invocation group name.
                 var parent = $(this).parents('tr[data-group-name]')[0];

                 if (!parent)
                     return; // do nothing.

                 updateInvocation(parent);
             });
         });
     }

     function updateInvocation(parent) {
         var $parent = $(parent);
         var invocationGroup = $parent.attr('data-group-name');

         // get selected value.
         var selectedElement = $parent.find('input.invocation-selected')[0];

         if (!selectedElement)
             return;

         var selected = $(selectedElement).is(':checked');

         if (!validateInvocationChoice($parent, invocationGroup, selected)) {
             if (selected)
                 $(selectedElement).attr('checked', false);

             return;
         }

         var url = settings.updateInvocationUrl + '?group=' + invocationGroup + '&selected=' + selected;

         doAjaxGet(url,
            settings.invocationsContainer,
            function () {
                if (settings.invocationUpdatedCallback)
                    settings.invocationUpdatedCallback(selectedElement, selected);

                showMessage('Updated invocation ' + invocationGroup + '.');
                bindInvocations(); // ensure these events are re bound to new html elements.

                showMessage('Invocation updated.');
            },
            function (data) {
                $(selectedElement).attr('checked', false);
                showErrorText('Failed to update invocation ' + invocationGroup + '.');
                showWarning(data);
            },
            false
        );
     }

     // Validate that the invocation choice is valid.
     function validateInvocationChoice(parent, invocationGroup, selected) {
         if (!selected || !settings.knownInvocationLimits)
             return true; // un-selecting or no limits is always a valid action.

         // get invocation colour andtype from parent
         var invocationSect = parent.attr('data-sect');
         var invocationType = parent.attr('data-type');

         // get sum of all invocations selected or attuned within this colour.
         var sumChecked = 0;

         sumChecked = parent.parent().find("tr[data-sect='" + invocationSect + "'][data-type='" + invocationType + "'] input[type=checkbox]:checked").length;

         // get allowed for this colour
         var allowedInvocations = eval('settings.knownInvocationLimits.' + invocationSect + "_" + invocationType);

         var valid = (allowedInvocations >= sumChecked);

         if (!valid)
             showMessage('Insufficient known invocations of sect ' + invocationSect + '.  Spend more status with this sect to know more invocations.');

         return valid;
     }

     function _refreshSects() {
         // reload the header container content via ajax.
         doAjaxGet(
                settings.sectsUrl,
                settings.sectsContainerSelector,
                function () {
                    // refresh jquery event binding.
                    //bindHeaderEvents();

                    if (settings.sectsRefreshedCallback)
                        settings.sectsRefreshedCallback();
                },
                showWarning);
     }

     function _refreshInvocations() {
         // reload the header container content via ajax.
         doAjaxGet(
                settings.refreshInvocationsUrl,
                settings.invocationsContainer,
                function () {
                    // refresh jquery event binding.
                    bindInvocations();

                    if (settings.invocationsCallback)
                        settings.invocationsCallback();
                },
                showWarning);
     }

 })(jQuery);